<!--
* @Author: xzh
* @Date: 2021-05-21 00:31:25
* @LastEditTime: 2021-05-21 10:09:32
* @LastEditors: xzh
* @Description: 组件描述
* @FilePath: /文件路径.vue
* 代码版权方：'政府采购信息网'
-->
<template>
<div>
<el-card>
    <el-form :model="formData" :rules="formRules" ref="myform" :inline="true" style="width:1150px">
        <el-row>
            <el-col :span="15">
                <el-form-item label="名称" prop="columnName">
                    <el-input v-model="formData.columnName" maxlength="60" show-word-limit 
                    type="textarea" style="width:500px"></el-input>
                </el-form-item>
                <el-form-item label="状态" style="margin-left: 20px;" >
                    <el-switch v-model="formData.columnStatus" :active-value="1" :inactive-value="0"/>
                </el-form-item>
                
            </el-col>
            <el-col v-if="columnId" :span="8">
                <el-form-item label="新建时间" style="margin-left: 20px;float: left;">
                    <span>{{formData.createTime ? new Date(formData.createTime).Format("yyyy-MM-dd hh:mm:ss") : '' }}</span>
                </el-form-item>
            </el-col>
            <el-col :span="13">
                <el-form-item label="备注">
                    <el-input v-model="formData.columnInfo" maxlength="60" 
                    type="textarea" show-word-limit style="width:500px"></el-input>
                </el-form-item>
            </el-col>
            <el-col v-if="columnId" :span="8" :offset="2">
                <el-form-item label="更新时间" style="margin-left: 20px;float: left;">
                    <span>{{formData.updateTime ? new Date(formData.updateTime).Format("yyyy-MM-dd hh:mm:ss") : ''}}</span>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="授课对象" prop="columnStudent">
                    <el-select allow-create filterable multiple v-model="formData.columnStudent" style="width:300px">
                        <el-option v-for="item in teachObjects" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="适合省份" prop="columnProvince">
                    <el-select filterable v-model="formData.columnProvince">
                        <el-option v-for="item in provinceOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="法律法规" prop="columnLabel">
                    <el-select allow-create filterable multiple v-model="formData.columnLabel" style="width:300px">
                        <el-option v-for="item in lawOption" :key="item.value+''" :label="item.label" :value="item.value+''"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="20">
                <el-form-item label="上线时间">
                    <el-select v-model="formData.columnPublishYear">
                        <el-option v-for="item in onlineTime" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="属性">
                    <el-select v-model="formData.columnProperty">
                        <el-option v-for="item in attributeOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="类型" prop="columnType">
                    <el-select v-model="formData.columnType" allow-create filterable multiple style="width:300px">
                        <el-option v-for="item in typeOption" :key="item.value+''" :label="item.label" :value="item.value+''"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row v-if="columnId" style="margin: 20px;">
            <el-col :span="24">
                <el-button type="primary" @click="updateColumnAction('myform')">保存</el-button>
            </el-col>
        </el-row>
        
    </el-form>
</el-card>
<el-card >
    <div slot="header">
        <span style="color:#00000000">.</span>
        <div style="float: left;"> 
            <span style="margin-right: 10px;">{{'视频总时长:'+makeTimeStr(dataSource.info.columnVideoTotal)}} </span>
            <span style="margin-right: 10px;">{{'随堂小考总量:' + dataSource.info.anchorCount}}</span>
            <span style="margin-right: 10px;">{{'单选:' + dataSource.info.columnRadio}}</span>
            <span style="margin-right: 10px;">{{'多选:' + dataSource.info.columnSelect}}</span>
            <span style="margin-right: 10px;">{{'判断:' + dataSource.info.columnJudge}}</span>
            <span style="margin-right: 10px;">{{'包含的讲师:' + dataSource.info.columnLecturer}}</span>
        </div>       
    </div>
    <el-table :data="dataSource.value" border>
        <el-table-column label="序号" align="center" type="index" :index="getIndex" width="80"></el-table-column>
        <el-table-column label="视频名称" align="center" width="500">
            <template slot-scope="scope">
                <el-select v-if="scope.$index < 1" v-model="scope.row.articleId" filterable 
                           @change="selectedVideo($event, scope.$index)" style="width:460px">
                    <el-option v-for="item in videoOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
                <span v-if="scope.$index > 0" >{{scope.row.articleTitle}}</span>
            </template>
        </el-table-column>
        <el-table-column label="讲师" align="center" width="300">
            <template slot-scope="scope">
                <el-select v-if="scope.$index < 1" v-model="scope.row.lecturerId" filterable 
                           @change="selectedTeacher($event, scope.$index)" style="width:260px">
                    <el-option v-for="item in teacherOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
                <span v-if="scope.$index > 0">{{scope.row.lecturer}}</span>
            </template>
        </el-table-column>
        <el-table-column label="时长" align="center">
            <template slot-scope="scope">{{makeTimeStr(scope.row.totalTime)}}</template>
        </el-table-column>
        <el-table-column label="类型" align="center">
            <template slot-scope="scope">{{makeVideoTypeStr(scope.row.articleType)}}</template>
        </el-table-column>
        <el-table-column label="视频顺序" align="center">
            <template slot-scope="scope">
                <el-input-number v-if="scope.$index < 1" v-model="scope.row.showIndex" controls-position="right" :min="0" style="width:100px"/>
                <span v-if="scope.$index > 0">{{scope.row.showIndex}}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
            <template slot-scope="scope">
                <el-button v-if="scope.$index < 1" type="primary" @click="addVideoAction(scope.row)">添加视频</el-button>
                <el-button v-if="scope.$index > 0" type="danger" @click="removeVideoAction(scope.row, scope.$index)">移除视频</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-row v-if="columnId" style="margin: 20px;">
        <el-col :span="24">
            <el-button @click="goBackAction">返回</el-button>
        </el-col>
    </el-row>
    <el-row v-else style="margin: 20px;">
        <el-col :span="3" :offset="8" >
            <el-button @click="goBackAction">返回</el-button>
            
        </el-col>
         <el-col :span="3" >
            <el-button type="primary" @click="saveColumnAction('myform')">保存</el-button>
         </el-col>
    </el-row>
</el-card>
</div>
</template>
 
<script>
Date.prototype.Format = function (fmt) { //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};

Array.prototype.insert = function(index,value){
    this.splice(index, 0, value);
};

// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { loadCmsOnlineClassDataList, loadCmsChinaList, loadCmsExamLabelList, 
         loadCmsLecturerDataList, loadCmsColumnData, saveCmsColumnDataInfo,
         deleteCmsColumnData, updateCmsColumn, saveCmsColumnData} from "@/api/study";
export default {
    components: {},
    props: {
        columnId: Number|String,
    },
    data () {
        var checkColumnStudent = (rule, val, callback) =>{
            if (val.length < 1) {
                return callback(new Error('请选择授课对象'));
            }else{
                callback();
            }
        };
        var checkColumnProvince = (rule, val, callback) => {
            if (val.length < 1) {
                return callback(new Error('请选择适合省份'));
            }else{
                callback();
            }
        };
        var checkColumnLabel = (rule, val, callback) => {
            if (val.length < 1) {
                return callback(new Error('请选择法律法规'));
            }else{
                callback();
            }
        };
        var checkColumnType = (rule, val, callback) => {
            if (val.length < 1) {
                return callback(new Error('请选择类型'));
            }else{
                callback();
            }
        };
        return {
            teachObjects:[
                {label: '采购人', value: '1'},
                {label: '集采机构', value: '2'},
                {label: '社会中介', value: '3'},
                {label: '评审专家', value: '4'},
                {label: '供应商', value: '5'},
                {label: '监管部门', value: '6'},
                {label: '其他', value: '7'},
            ],
            provinceOption: [],
            lawOption: [],
            onlineTime:[
                {label: '2019', value: '2019'},
                {label: '2020', value: '2020'},
                {label: '2021', value: '2021'},
                {label: '2022', value: '2022'},
                {label: '2023', value: '2023'},
                {label: '2024', value: '2024'},
                {label: '2025', value: '2025'},
                {label: '2026', value: '2026'},
            ],
            attributeOption:[
                {label: '常规栏目', value: 1},
                {label: '特定栏目', value: 2},
            ],
            typeOption:[
                {label: '法规讲解', value: 1},
                {label: '案例讲解', value: 2},
                {label: '动漫视频', value: 3},
                {label: '实物讲解', value: 4},
                {label: '问答讲解', value: 5},
                {label: '其他', value: 6},
            ],
            formData:{
                columnName: '',//栏目名称
                columnStatus: 1,//栏目状态
                createTime: '',//创建时间
                updateTime: '',//更新时间
                columnInfo: '',//栏目备注
                columnStudent: [],//授课对象
                columnProvince: '',//适合省份
                columnLabel: [],//法律法规
                columnPublishYear: new Date().getFullYear(),//上线时间
                columnProperty: 1,//属性
                columnType: [],//类型
            },
            formRules:{
                columnName:[
                    { required: true, message: '请输入栏目名称', trigger: 'blur' },
                    { min: 1, max: 60, message: '长度在60个字符以内', trigger: 'blur' }
                ],
                columnStudent: [
                    { required: true, validator: checkColumnStudent, trigger: 'change' },
                ],
                columnProvince: [
                    { required: true, validator: checkColumnProvince, trigger: 'change' },
                ],
                columnLabel: [
                    { required: true, validator: checkColumnLabel, trigger: 'change' },
                ],
                columnType: [
                    { required: true, validator: checkColumnType, trigger: 'change' },
                ]
            },
    
            videoOption:[],
            videoType:[
                {label: '视频', value: 1},
                {label: '文章', value: 1},
                {label: '音频', value: 1},
                {label: '图集', value: 1}
            ],
            teacherOption:[],
            dataSource:{
                info:{
                    columnVideoTotal: 0,//视频总时长
                    anchorCount: 0,//随堂小考总量
                    columnRadio: 0,//单选
                    columnSelect: 0,//多选
                    columnJudge: 0,//判断
                    columnLecturer:'',//包含的讲师
                },
                value:[
                    {
                        articleTitle:'',//视频标题
                        articleId: '',//视频ID
                        lecturer: '',//讲师
                        lecturerId: '',//讲师id
                        totalTime: '',//视频时长
                        articleType: '',//视频类型
                        showIndex: 0,//视频顺序
                    }
                ],
            },
        }
    },
// 监听属性 类似于data概念
    computed: {}, 
// 监控data中的数据变化
    watch: {},
// 方法集合
    methods: {
        loadVideoData(query){
            console.log(query);
            if (query != null) {
                loadCmsOnlineClassDataList({searchTitle: query}).then(response => {
                    if(response.code == 200){
                        this.videoOption = response.data;
                    }
                }).catch(error => {

                });
            }
        },

        loadTeacherData(query){
            if(query != null){
                loadCmsLecturerDataList({searchTitle: query}).then(response => {
                    if(response.code == 200){
                        this.teacherOption = response.data;
                    }
                })
            }
        },

        loadProvinceData(cell){
            loadCmsChinaList().then(response => {
                if(response.code == 200){
                    // this.provinceOption = response.data
                    this.provinceOption = response.data;
                }else{
                    this.$message.warning(response.message);
                }
                cell();
            }).catch(error => {
                console.log(error);
                this.$message.error(error);
            });
        },

        loadLawData(cell){
            loadCmsExamLabelList().then(response => {
                if(response.code == 200){
                    this.lawOption = response.data[0].children;
                }else{
                    this.$message.warning(response.message);
                }
                cell();
            }).catch(error => {
                console.log(error);
                this.$message.error(error);
            });
        },

        

        loadData(){
            loadCmsColumnData({id: this.columnId}).then(response => {
                if (response.code == 200) {
                    this.formData.columnName = response.data.columnName;
                    this.formData.columnStatus = response.data.columnStatus;
                    this.formData.createTime = response.data.createTime;
                    this.formData.updateTime = response.data.updateTime;
                    this.formData.columnInfo = response.data.columnInfo;
                    this.formData.columnStudent = response.data.columnStudent.split(',');
                    this.formData.columnProvince = response.data.columnProvince + '';
                    this.formData.columnLabel = response.data.columnLabel.split(',');
                    this.formData.columnPublishYear = response.data.columnPublishYear;
                    this.formData.columnProperty = response.data.columnProperty;
                    this.formData.columnType = (response.data.columnType + '').split(',');

                    this.dataSource.info.columnVideoTotal = response.data.columnVideoTotal;

                    this.dataSource.info.columnRadio = response.data.columnRadio;
                    this.dataSource.info.columnSelect = response.data.columnSelect;
                    this.dataSource.info.columnJudge = response.data.columnJudge;
                    var lecturers = [...new Set(response.data.columnLecturer)];
                    this.dataSource.info.columnLecturer = lecturers.join();
                    this.dataSource.value = [{articleTitle:'',articleId: '',
                                              lecturer: '',lecturerId: '',
                                              totalTime: '',articleType: '',
                                              showIndex: ''}]
                    this.dataSource.value.push(...response.data.dataList);
                    this.dataSource.info.anchorCount = 0;
                    for (let i = 0; i < response.data.dataList.length; i++) {
                        const ie = response.data.dataList[i];
                        this.dataSource.info.anchorCount += ie.anchorCount;
                    }
                    
                }
            }).catch(error => {

            });
        },

        getIndex(index){
            if (index == 0) {
                return '#';
            }
            return index;
        },

        makeTimeStr(val){
            let h = parseInt(val / 60 / 60 % 24);
            h = h < 10 ? '0' + h : h;
            let m = parseInt(val / 60 % 60);
            m = m < 10 ? '0' + m : m;
            let s = parseInt(val % 60);
            s = s < 10 ? '0' + s : s;

            return h + ':' + m + ':' + s;
        },

        makeVideoTypeStr(val){
            for (let i = 0; i < this.videoType.length; i++) {
                const ie = this.videoType[i];
                if (val == ie.value) {
                    return ie.label;
                }
            }
            return '暂无';
        },
        updateColumnAction(formname){
            var param = {
                columnParam:{
                    id: this.columnId,
                    columnName: this.formData.columnName,
                    columnStatus: this.formData.columnStatus,
                    columnInfo: this.formData.columnInfo,
                    columnStudent: this.formData.columnStudent.join(),
                    columnLabel: this.formData.columnLabel.join(),
                    columnProvince: this.formData.columnProvince,
                    columnPublishYear: this.formData.columnPublishYear,
                    columnProperty: this.formData.columnProperty,
                    columnType: this.formData.columnType.join(),
                }
            };
            this.$refs[formname].validate(valid => {
                if(valid){
                    updateCmsColumn(param).then(response => {
                        if(response.code == 200){
                            this.$message.success(response.message);
                        }else{
                            this.$message.warning(response.message);
                        }
                    });
                }else{
                    return false;
                }
            });
        },

        selectedVideo(val, index){
            for (let i = 0; i < this.videoOption.length; i++) {
                const ie = this.videoOption[i];
                if(ie.value == val){
                    this.dataSource.value[index].articleTitle = ie.label;
                    this.dataSource.value[index].totalTime = ie.studyTime;
                    this.dataSource.value[index].articleType = ie.type;
                    this.dataSource.value[index].lecturer = ie.lecturer;
                    this.dataSource.value[index].columnJudge = ie.columnJudge;
                    this.dataSource.value[index].columnRadio = ie.columnRadio;
                    this.dataSource.value[index].columnSelect = ie.columnSelect;
                }
            }
        },

        selectedTeacher(val, index){
            for (let i = 0; i < this.teacherOption.length; i++) {
                const ie = this.teacherOption[i];
                if(ie.value == val){
                    this.dataSource.value[index].lecturer = ie.label;
                }
            }
        },

        addVideoAction(data){

            if (data.articleId.length == 0) {
                this.$message.error('请选择视频名称');
                return;
            }else if(data.lecturerId.length == 0){
                this.$message.error('请选择讲师');
                return;
            }else if(data.showIndex == 0){
                this.$message.error('请选择排序序号');
                return;
            } 
            var param = {
                dataParam:{
                    columnId: this.columnId,
                    articleId: data.articleId,
                    lecturerId: data.lecturerId,
                    showIndex: data.showIndex
                }
            };
            if(this.columnId && (this.columnId+'').length > 0){
                saveCmsColumnDataInfo(param).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        this.loadData()
                    }else{
                        this.$message.warning(response.message);
                    }
                });
            }else{
                
                var nd = {
                    articleTitle: data.articleTitle,
                    articleId: data.articleId,
                    lecturer: data.lecturer,
                    lecturerId: data.lecturerId,
                    totalTime: data.totalTime,
                    articleType: data.articleType,
                    showIndex: data.showIndex,
                    columnJudge: data.columnJudge,
                    columnRadio: data.columnRadio,
                    columnSelect: data.columnSelect
                }
                var oldDatas = this.dataSource.value;
                var insertIndex = -1;
                if(nd.showIndex == 0){
                    this.$message.error('请选择排序序号');
                    return;
                } 
                for (let i = 1; i < oldDatas.length; i++) {
                    const ei = oldDatas[i];
                    if(ei.articleId == nd.articleId && i > 0){
                        this.$message.warning('已经添加过该视频');
                        return;
                    }
                    if (nd.showIndex >= ei.showIndex) {
                        insertIndex = i;
                        break;
                    }
                }
                
                console.log('->->->',insertIndex);
                if (insertIndex <= 0) {
                    this.dataSource.value.insert(1,nd);
                }else{
                    this.dataSource.value.insert(insertIndex,nd);
                }
                
                var lecturer = [];
                var radio = 0;
                var select = 0;
                var judge = 0;
                var totalTime = 0;
                for (let i = 1; i < this.dataSource.value.length; i++) {
                    const ei = this.dataSource.value[i];
                    lecturer.push(ei.lecturer);
                    radio = ei.columnRadio + radio;
                    select = ei.columnSelect + select;
                    judge = ei.columnJudge + judge;
                    totalTime = parseInt(ei.totalTime + '') + parseInt(totalTime + '');
                }
                var l = [...new Set(lecturer)];
                this.dataSource.info.columnLecturer = l.join();
                this.dataSource.info.columnRadio = radio;
                this.dataSource.info.columnSelect = select;
                this.dataSource.info.columnJudge = judge;
                this.dataSource.info.anchorCount = radio + select + judge;
                this.dataSource.info.columnVideoTotal = totalTime;
                data.articleTitle = '';
                data.articleId = '';
                data.lecturer = '';
                data.lecturerId = '';
                data.totalTime = 0;
                data.articleType = '';
                data.showIndex = 0;
            }
            
        },

        removeVideoAction(data, index){
            if(this.columnId && (this.columnId+'').length > 0){
                var param = {columnId:this.columnId, id:data.id};
                deleteCmsColumnData(param).then(response => {
                    if (response.code == 200) {
                        this.$message.success(response.message);
                        this.loadData()
                    }else{
                        this.$message.warning(response.message);
                    }
                });
            }else{
                this.dataSource.value.splice(index,1);
            }
            
        },

        saveColumnAction(formname){
            var articleList = [];
            if (this.dataSource.value.length > 1) {
                for (let i = this.dataSource.value.length-1; i >= 0; i--) {
                    const ie = this.dataSource.value[i];
                    var article = {};
                    article.articleId = ie.articleId;
                    article.lecturerId = ie.lecturerId;
                    article.showIndex = ie.showIndex;
                    articleList.push(article);
                }
            }
            var param = {
                columnParam:{
                    columnName: this.formData.columnName,
                    columnStatus: this.formData.columnStatus,
                    columnInfo: this.formData.columnInfo,
                    columnStudent: this.formData.columnStudent.join(),
                    columnLabel: this.formData.columnLabel.join(),
                    columnProvince: this.formData.columnProvince,
                    columnPublishYear: this.formData.columnPublishYear,
                    columnProperty: this.formData.columnProperty,
                    columnType: this.formData.columnType.join(),
                    articleList: articleList,
                }
            };
            this.$refs[formname].validate(valid => {
                if(valid){
                    saveCmsColumnData(param).then(response => {
                        if(response.code == 200){
                            this.$message.success(response.message);
                            this.$jump.back();
                        }else{
                            this.$message.warning(response.message);
                        }
                    });
                }else{
                    return false;
                }
            });
        },

        goBackAction(){
            this.$confirm("返回将不会保存修改内容").then(response => {
                this.$jump.back();
            }).catch(err => {
                console.log(err);
            });
        },
    },
/*------生命周期-------*/
//创建完成（可以访问当前this实例）
    created() {
        this.loadProvinceData(() => {
            this.loadLawData(() => {
                if(this.columnId && (this.columnId+'').length > 0){
                    this.loadData();
                }
                this.loadVideoData('');
                this.loadTeacherData('');
            });
        });
    },
//挂载完成（可以访问DOM元素）
    mounted() {},
//创建之前
    beforeCreate() {},
//挂载之前
    beforeMount() {},
//更新之前
    updated() {},
//销毁之前
    beforeDestroy() {},
//销毁完成
    destroyed() {},
//如果页面有keep-alive缓存功能，这个函数会触发
    activated() {},
};
</script>
 
<style  scoped>

</style>